const md5 = require("md5");
const jwt = require("jwt-simple");
const KEY = "&^%&*";
const request = require("request");
const querystring = require("querystring")
module.exports.getRandom = function(min,max){
    return Math.floor(Math.random()*(max-min+1)+min)
}
// 获取当前时间   年-月-日 时:分:秒
module.exports.getNowTime = function () {
    const date = new Date();
    return date.getFullYear()+"-"
        + (date.getMonth()+1).toString().padStart(2,0) + "-"
        +date.getDate().toString().padStart(2,0) + " "
        +date.getHours().toString().padStart(2,0) + ":"
        +date.getMinutes().toString().padStart(2,0) + ":"
        +date.getSeconds().toString().padStart(2,0);
}
// res:响应对象
module.exports.json = function (res,ok = -1,msg = "网络连接错误") {
    res.json({
        ok,
        msg
    })
}
//加密密码
module.exports.enMd5 =function(passWord){
    const str = "*&%*&^%*&";
    // console.log(md5(passWord+str))
    return md5(passWord+str)
};
// console.log(md5("123456"+"*&%*&^%*&"))
//生成token
module.exports.encode =function(info){
    return jwt.encode({
        ...info,
        ...{
            lastTime:Date.now()+1000*60*60*14
        }
    },KEY)
};
//验证token
module.exports.decode = function (token) {
    try{
        const info = jwt.decode(token,KEY);
        // console.log("info",info);
        // 判断是否过期
        if(info.lastTime < Date.now()){
            // 过期了
            return {
                ok:1,
                msg:"过期了"
            }
        }else{
            // 正确
            return {
                ok:3,
                msg:"正常",
                info
            }
        }
    }catch(err){
        // token异常
        return {
            ok:2,
            msg:"token异常"
        }
    }
}

module.exports.send = function(mobile){
    const str = this.getRandom(100000,999999);
    console.log("您的验证码是"+str)
    const params ={
        mobile,
        tpl_id:"197714",
        tpl_value:"#code#="+str,
        key:"b2c4f5a91194ea24befc1178053ff0ba"
    }
    const url ='http://v.juhe.cn/sms/send?'+querystring.stringify(params);
    request(url, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            console.log(body) // 打印接口返回内容

            var jsonObj = JSON.parse(body); // 解析接口返回的JSON内容
            console.log(jsonObj)
        } else {
            console.log('请求异常');
        }
    })
}
//将一维数组转为二维数组
module.exports.changeArr = function(arr,len=10){
    const newArr = [];
    for(var i =0;i<arr.length;i+=len){
        newArr.push(arr.slice(i,i+len))
    }
    return newArr
}

